#!/usr/bin/env bash

export DEBIAN_FRONTEND=noninteractive

# update ubuntu

sudo aptitude update -q

sudo apt-get install -y build-essential tcl8.5 curl python-software-properties git > /dev/null 2>&1

# install io.js in fact just run this is enough

sudo add-apt-repository ppa:chris-lea/node.js > /dev/null 2>&1

echo -e "\n--- Installing NodeJS and NPM ---\n"

sudo apt-get -y install nodejs > /dev/null 2>&1
sudo curl --silent https://npmjs.org/install.sh | sh > /dev/null 2>&1

# sudo wget -nv bit.ly/iojs-dev -O /tmp/iojs-dev.sh; bash /tmp/iojs-dev.sh

# install upstart

sudo aptitude install -q -y -f install upstart

sudo cp /var/www/upstart.development.conf /etc/init/<%= appname %>.conf

# Install nginx

sudo aptitude install -q -y -f nginx

sudo ln -s /var/www/deploy/nginx.development.conf /etc/nginx/sites-enabled/development.conf

sudo rm /etc/nginx/sites-enabled/default

echo -e 'nginx setup completed, now start upstart for nodejs app\n\n'

<% if (answers.install.mysql) { %>

# Variables
APPENV=local
DBHOST=localhost
DBNAME=dbname
DBUSER=dbuser
DBPASSWD=test123

# setup mysql - this script is from https://gist.github.com/rrosiek/8190550

echo -e "\n--- Updating packages list ---\n"
sudo apt-get -qq update

echo -e "\n--- Install MySQL specific packages and settings ---\n"
echo "mysql-server mysql-server/root_password password $DBPASSWD" | debconf-set-selections
echo "mysql-server mysql-server/root_password_again password $DBPASSWD" | debconf-set-selections
echo "phpmyadmin phpmyadmin/dbconfig-install boolean true" | debconf-set-selections
echo "phpmyadmin phpmyadmin/app-password-confirm password $DBPASSWD" | debconf-set-selections
echo "phpmyadmin phpmyadmin/mysql/admin-pass password $DBPASSWD" | debconf-set-selections
echo "phpmyadmin phpmyadmin/mysql/app-pass password $DBPASSWD" | debconf-set-selections
echo "phpmyadmin phpmyadmin/reconfigure-webserver multiselect none" | debconf-set-selections
apt-get -y install mysql-server-5.5 > /dev/null 2>&1

echo -e "\n--- Setting up our MySQL user and db ---\n"
mysql -uroot -p$DBPASSWD -e "CREATE DATABASE $DBNAME"
mysql -uroot -p$DBPASSWD -e "grant all privileges on $DBNAME.* to '$DBUSER'@'localhost' identified by '$DBPASSWD'"

# Uncommon this if you want to setup a phpmyadmin etc - remember this will install apache as well, which will crash with nginx. Change apache default port to something other than 80!
# echo -e "\n--- Installing PHP-specific packages ---\n"
# apt-get -y install php5 apache2 libapache2-mod-php5 php5-curl php5-gd php5-mcrypt php5-mysql php-apc phpmyadmin > /dev/null 2>&1
#echo -e "\n--- Enabling mod-rewrite ---\n"
#a2enmod rewrite > /dev/null 2>&1

#echo -e "\n--- Allowing Apache override to all ---\n"
#sed -i "s/AllowOverride None/AllowOverride All/g" /etc/apache2/apache2.conf

#echo -e "\n--- Setting document root to public directory ---\n"
#rm -rf /var/www
#ln -fs /vagrant/public /var/www

#echo -e "\n--- We definitly need to see the PHP errors, turning them on ---\n"
#sed -i "s/error_reporting = .*/error_reporting = E_ALL/" /etc/php5/apache2/php.ini
#sed -i "s/display_errors = .*/display_errors = On/" /etc/php5/apache2/php.ini

#echo -e "\n--- Turn off disabled pcntl functions so we can use Boris ---\n"
#sed -i "s/disable_functions = .*//" /etc/php5/cli/php.ini

#echo -e "\n--- Configure Apache to use phpmyadmin ---\n"
#echo -e "\n\nListen 81\n" >> /etc/apache2/ports.conf
#cat > /etc/apache2/conf-available/phpmyadmin.conf << "EOF"
#<VirtualHost *:81>
#    ServerAdmin webmaster@localhost
#    DocumentRoot /usr/share/phpmyadmin
#    DirectoryIndex index.php
#    ErrorLog ${APACHE_LOG_DIR}/phpmyadmin-error.log
#    CustomLog ${APACHE_LOG_DIR}/phpmyadmin-access.log combined
#</VirtualHost>
#EOF
#a2enconf phpmyadmin > /dev/null 2>&1

#echo -e "\n--- Add environment variables to Apache ---\n"
#cat > /etc/apache2/sites-enabled/000-default.conf <<EOF
#<VirtualHost *:8080>
#    DocumentRoot /var/www
#    ErrorLog \${APACHE_LOG_DIR}/error.log
#    CustomLog \${APACHE_LOG_DIR}/access.log combined
#    SetEnv APP_ENV $APPENV
#    SetEnv DB_HOST $DBHOST
#    SetEnv DB_NAME $DBNAME
#    SetEnv DB_USER $DBUSER
#    SetEnv DB_PASS $DBPASSWD
#</VirtualHost>
#EOF

#echo -e "\n--- Restarting Apache ---\n"
#service apache2 restart > /dev/null 2>&1

#echo -e "\n--- Installing Composer for PHP package management ---\n"
#curl --silent https://getcomposer.org/installer | php > /dev/null 2>&1
#mv composer.phar /usr/local/bin/composer

echo -e "\n--- Add environment variables locally for artisan ---\n"
cat >> /home/vagrant/.bashrc <<EOF
# Set envvars
export APP_ENV=$APPENV
export DB_HOST=$DBHOST
export DB_NAME=$DBNAME
export DB_USER=$DBUSER
export DB_PASS=$DBPASSWD
EOF

<% } %>

<% if (answers.install.postgresql) { %>

# setup postgresql

echo "Installing Postgresql package dependencies"

sudo apt-get -qq update

sudo apt-get install -y apr-devel apr-util-devel autoconf automake curl-devel \
                    g++ gcc gcc-c++ git glibc-headers httpd-devel libxml2 \
                    libxml2-devl libxslt libxslt-devel libyaml-devel make \
                    openssl-devel patch readline \
                    readline-devel zlib zlib-devel

echo "Installing Posgtgresql Server and dependencies"
sudo apt-get install -y http://yum.postgresql.org/9.4/redhat/rhel-6-x86_64/pgdg-centos94-9.4-1.noarch.rpm
sudo apt-get install -y postgresql94 postgresql94-devel postgresql94-server postgresql94-contrib libpq-dev

###########################################
## Database setup
###########################################

POSTGRES_RUNNING=$(service postgresql-9.4 status | egrep  "postgresql.*running" | wc -l)
if [ "$POSTGRES_RUNNING" -ne 1 ]; then

echo 'Starting Postgres'
  sudo /sbin/service postgresql-9.4 initdb
  sudo /sbin/service postgresql-9.4 start
  sudo /sbin/chkconfig postgresql-9.4 on
else
	echo "Postgres is running"
fi

DATABASE_YML="/vagrant/config/database.yml"
APP_DB_USERNAME="blog_user"
APP_DB_PASSWORD="blog_user91x91x"

if [ -f $DATABASE_YML ];
then
	echo "File $DATABASE_YML exists."
else
	echo "File $DATABASE_YML does not exist, creating."
# create role myapp with createdb login password 'password1';
_EOF_

echo "Creating postgres user:"
  CREATE_USER_SQL="CREATE ROLE $APP_DB_USERNAME PASSWORD '$APP_DB_PASSWORD' CREATEDB INHERIT LOGIN;"
  sudo -u postgres psql --command="$CREATE_USER_SQL"
  ALTER_USER_SQL="ALTER USER $APP_DB_USERNAME WITH ENCRYPTED PASSWORD '$APP_DB_PASSWORD'"
  sudo -u postgres psql --command="$ALTER_USER_SQL"
  ALTER_POSTGRES_USER_SQL="ALTER USER postgres WITH ENCRYPTED PASSWORD 'postgres'"
  sudo -u postgres psql --command="$ALTER_POSTGRES_USER_SQL"
echo "Updating postgresql connection info"
  sudo cp /var/lib/pgsql/9.4/data/pg_hba.conf .
  sudo chmod 666 pg_hba.conf
  sed 's/ident/md5/' < pg_hba.conf > pg_hba2.conf
echo 'host    all             all             0.0.0.0/0               md5' >> pg_hba2.conf
  sudo cp pg_hba2.conf /var/lib/pgsql/9.4/data/pg_hba.conf
  sudo chmod 600 /var/lib/pgsql/9.4/data/pg_hba.conf
  sudo cp /var/lib/pgsql/9.4/data/postgresql.conf .
  sudo chmod 666 postgresql.conf
  sed "s/^#listen_addresses.*$/listen_addresses = '0.0.0.0'/" < postgresql.conf > postgresql2.conf
  sudo cp postgresql2.conf /var/lib/pgsql/9.4/data/postgresql.conf
  sudo chmod 600 /var/lib/pgsql/9.4/data/postgresql.conf
  sudo /sbin/service postgresql-9.4 restart
# psql -U
  cat > $DATABASE_YML <<_EOF_
  default: &default
    adapter: postgresql
    encoding: utf8
    min_messages: warning
    pool: 5
    timeout: 5000
    username: $APP_DB_USERNAME
    password: $APP_DB_PASSWORD
    host: localhost
  development:
    <<: *default
    database: blog_development
  test:
    <<: *default
    database: blog_test
  production:
    <<: *default
    database: blog_production
_EOF_
fi

<% } %>

<% if (answers.install.mariadb) { %>

sudo apt-get install -y mariadb-server

<% } %>

<% if (answers.install.sqlite) { %>

# setup sqlite

sudo apt-get install -y sqlite3 libsqlite3-dev

<% } %>

<% if (answers.install.couchdb) { %>

# setup couchdb - this is why its superior!

sudo apt-get install -y couchdb

<% } %>

<% if (answers.install.redis) { %>

# setup redis, script from https://github.com/mdevilliers/vagrant-redis/blob/master/init.sh

sudo apt-get update > /dev/null

sudo apt-get -y install make

sudo mkdir /opt/redis

cd /opt/redis
# Use latest stable
sudo wget http://download.redis.io/redis-stable.tar.gz
# Only update newer files
sudo tar -xz --keep-newer-files -f redis-stable.tar.gz

cd redis-stable
make
make install
sudo rm /etc/redis.conf
sudo mkdir -p /etc/redis
sudo mkdir /var/redis
sudo chmod -R 777 /var/redis
sudo useradd redis

sudo cp -u /vagrant/redis.conf /etc/redis/6379.conf
sudo cp -u /vagrant/redis.init.d /etc/init.d/redis_6379

sudo update-rc.d redis_6379 defaults

sudo chmod a+x /etc/init.d/redis_6379
sudo /etc/init.d/redis_6379 start

<% } %>

<% if (answers.install.mongodb) { %>

echo -e "\n\n--- INSTALL MONGO --\n\n";

sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10

echo "deb http://repo.mongodb.org/apt/ubuntu "$(lsb_release -sc)"/mongodb-org/3.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.0.list

sudo apt-get update

sudo apt-get install -y mongodb-org

# setup a data folder for mongo

sudo mkdir -p /data/db

echo "If you need to allow mongodb connection from outside of the virtual box, you must edit the /etc/mongod.conf see /vagrant/README.md for more details\r\n";

<% } %>

sudo start /etc/init/<%= appname %>

sudo service nginx restart

echo -e "\n\n--- Provisioning completed. Bye! ---\n\n"
